using System;
using System.IO;

namespace LIB
{
	/// <summary>
	/// Summary description for FileLog.
	/// </summary>
	public class FileLog
	{
		#region Private Parameter
		private bool active = false;
		// filesize defaults to 1 MB
		private long filesize = 1024000;
		private String fileExtension = "";
		private String endLine = "\n"; // the system-specific end-of-line character
		private String fileName = "";
		private String fileDir = "";

		private FileStream logFile;
		private StreamWriter fileOut;
		private char currentFileIndex = '0';

		private static String[] WEEK_DAYS = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
		private static String[] MONTHS = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
		#endregion

		#region Protected Parameter and method
		protected void setCurrentFileIndex(char c)        { currentFileIndex = c; }
		protected void setFileDir(String fd)              { fileDir = fd;    }
		protected void setFileName(String fnr)            { fileName = fnr;}
		public void setFileSize(int size)                 { filesize = size;}
		protected void setFileExtension(String extension) { fileExtension = extension;}
		protected char getCurrentFileIndex()   { return currentFileIndex; }
		protected String getFileDir()       { return fileDir; }
		protected String getFileName()      { return fileName; }
		protected String getFileExtension() { return(fileExtension); }
		protected String getFullName() 
		{
			return getFileDir() +
				getFileName() +
				getCurrentFileIndex() +
				getFileExtension();
		}
		#endregion

		#region active process
		public void activate()    { active = true; }
		public void deactivate()  { active = false; }
		public bool isActive() { return active; }
		#endregion
		
		#region Constructor of FileLog and finalize
		public FileLog()
		{
			endLine = "\n";//System.getProperty("line.separator","");
		}

		public FileLog(String dir, String name)
		{
			endLine = "\n";//System.getProperty("line.separator","");
			setCurrentFileIndex('0');
			setFileDir(dir);
			if (name != "") 
			{
				setFileName(name.Substring(0,name.Length-4));
				setFileExtension(name.Substring(name.Length-4));
				openFile(getFullName());
			} 
			else 
			{
				deactivate();
			}
		}

		public void finalize()
		{
			try 
			{
				fileOut.Flush();
				fileOut.Close();
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine( e.ToString());
				// too late for exceptions
			}
		}
		#endregion
		
		protected void openFile(String filename)
		{
			lock(this)
			{
				try 
				{
					if(logFile!=null)
					{
						logFile.Close ();
						logFile=null;
					}
					logFile = new FileStream(filename,FileMode.OpenOrCreate, FileAccess.ReadWrite);
					fileOut = new StreamWriter( logFile );
					fileOut.BaseStream.Seek( 0, SeekOrigin.End );
				} 
				catch (Exception e) 
				{
					System.Console.WriteLine("The file stream could not be opened in openFile() " + e.ToString());
				}
			}
		}

		private void changeFile()
		{
	
			if (getCurrentFileIndex()<'2') 
			{
				setCurrentFileIndex((char)((int)(getCurrentFileIndex()+1)));
			} 
			else 
			{
				setCurrentFileIndex('0');
			}

			try 
			{
				openFile(getFullName());
			} 
			catch(Exception e) 
			{
				System.Console.WriteLine("Error setting fileOut to next file in changeFile() " + e);
			}
		}

		public void genericWrite(String msg)
		{
			lock(this)
			{
				if (logFile==null) return;
				long size = logFile.Length;
				try 
				{
					if (size >= filesize) 
					{
						changeFile();
					}
					String tmStamp = getLineTimeStamp();
					fileOut.Write (tmStamp+"# "+msg+endLine);
					fileOut.Flush();
				} 
				catch(Exception e) 
				{
					System.Console.WriteLine("Event log failure in genericWrite() "+e.ToString());
				}
			}
		}


		/**
		 * Paolo - increased resolution.
		 */
		public static String getLineTimeStamp()
		{
			return System.DateTime.Now.ToString("yyyyMMddHHmmss");
		}
		protected static String zeroPad(int length,String toPad)
		{
			int numberOfZeroes = length - toPad.Length;
			for(int counter=0;counter<numberOfZeroes;counter++) 
			{
				toPad = "0" + toPad;
			}
			return toPad;
		}

		protected void blankLine()
		{
			lock(this)
			{
				try 
				{
					if (logFile.Length < filesize)
					{
						fileOut.Write(endLine);
						fileOut.Flush();
					}
				} 
				catch(Exception e) 
				{
					System.Console.WriteLine("Event log failure in blankLine() "+e);
				}
			}
		}
	}
}
